package com.atguigu.tingshu.account.service.impl;

import com.atguigu.tingshu.account.mapper.RechargeInfoMapper;
import com.atguigu.tingshu.account.mapper.UserAccountDetailMapper;
import com.atguigu.tingshu.account.mapper.UserAccountMapper;
import com.atguigu.tingshu.account.receiver.AccountReceiver;
import com.atguigu.tingshu.account.service.UserAccountService;
import com.atguigu.tingshu.common.constant.SystemConstant;
import com.atguigu.tingshu.model.account.RechargeInfo;
import com.atguigu.tingshu.model.account.UserAccount;
import com.atguigu.tingshu.model.account.UserAccountDetail;
import com.atguigu.tingshu.vo.account.AccountDeductVo;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;

@Slf4j
@Service
@SuppressWarnings({"all"})
public class UserAccountServiceImpl extends ServiceImpl<UserAccountMapper, UserAccount> implements UserAccountService {

    @Autowired
    private UserAccountMapper userAccountMapper;

    @Autowired
    private UserAccountDetailMapper userAccountDetailMapper;

    @Autowired
    private RechargeInfoMapper rechargeInfoMapper;

    /**
     * 初始化用户账户
     * 当用户注册或特定情况下需要初始化账户时调用此方法
     * 该方法为用户账户设置初始值，包括用户ID、总金额和可用金额
     *
     * @param userId 用户ID，用于标识和关联用户信息
     */
    @Override
    public void initUserAccount(Long userId) {
        // 创建UserAccount实例，用于存储用户账户信息
        UserAccount userAccount = new UserAccount();
        // 设置用户ID，关联到特定用户
        userAccount.setUserId(userId);
        // 设置总金额为1000，作为初始余额
        userAccount.setTotalAmount(new BigDecimal("1000"));
        // 设置可用金额为1000，与总金额相等，表示所有资金均可使用
        userAccount.setAvailableAmount(new BigDecimal("1000"));
        // 调用Mapper方法插入用户账户信息到数据库
        userAccountMapper.insert(userAccount);
    }

    /**
     * 获取用户可用金额
     *
     * @param userId
     * @return
     */
    @Override
    public BigDecimal getAvailableAmount(Long userId) {
        LambdaQueryWrapper<UserAccount> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(UserAccount::getUserId, userId).select(UserAccount::getAvailableAmount);
        UserAccount userAccount = userAccountMapper.selectOne(lambdaQueryWrapper);
        // 返回用户可用金额
        return userAccount.getAvailableAmount();
    }

    /**
     * 检查及扣减账户余额
     *
     * @param accountDeductVo
     * @return
     */
    @Override
    @Transactional
    public boolean checkAndDeduct(AccountDeductVo accountDeductVo) {
        // 执行sql语句
        int result = userAccountMapper.updateCheckAndDeduct(accountDeductVo.getUserId(), accountDeductVo.getAmount());
        if (result > 0) {
            // 记录当前账户资金流向
            this.addUserAccountDetail(
                    accountDeductVo.getUserId(),
                    accountDeductVo.getContent(),
                    SystemConstant.ACCOUNT_TRADE_TYPE_MINUS,
                    accountDeductVo.getAmount(),
                    accountDeductVo.getOrderNo());
            return true;
        }
        return false;
    }

    private void addUserAccountDetail(Long userId, String content, String typeMinus, BigDecimal amount, String orderNo) {
        UserAccountDetail userAccountDetail = new UserAccountDetail();
        userAccountDetail.setUserId(userId);
        userAccountDetail.setTitle(content);
        userAccountDetail.setTradeType(typeMinus);
        userAccountDetail.setAmount(amount);
        userAccountDetail.setOrderNo(orderNo);
        userAccountDetailMapper.insert(userAccountDetail);
    }

    /**
     * 充值支付成功
     *
     * @param orderNo
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void rechargePaySuccess(String orderNo) {
        //  充值成功要做什么? 修改状态, 增加余额; 记录充值记录
        RechargeInfo rechargeInfo = rechargeInfoMapper.selectOne(new LambdaQueryWrapper<RechargeInfo>().eq(RechargeInfo::getOrderNo, orderNo));
        if (null != rechargeInfo && rechargeInfo.getRechargeStatus().equals(SystemConstant.ORDER_STATUS_UNPAID)) {
            //  更新为已支付
            rechargeInfo.setRechargeStatus(SystemConstant.ORDER_STATUS_PAID);
            this.rechargeInfoMapper.updateById(rechargeInfo);
            //  增加交易金额；
            userAccountMapper.updateUserAccount(rechargeInfo.getUserId(), rechargeInfo.getRechargeAmount());
            //  记录充值记录：
            this.addUserAccountDetail(rechargeInfo.getUserId(), "充值", SystemConstant.ACCOUNT_TRADE_TYPE_DEPOSIT, rechargeInfo.getRechargeAmount(), orderNo);
        }
    }

    /**
     * 查看充值记录
     *
     * @param detailPage
     * @param userId
     * @return
     */
    @Override
    public IPage<UserAccountDetail> findUserRechargePage(Page<UserAccountDetail> detailPage, Long userId) {
        return userAccountDetailMapper.selectPage(detailPage, new LambdaQueryWrapper<UserAccountDetail>().eq(UserAccountDetail::getUserId, userId).eq(UserAccountDetail::getTradeType, SystemConstant.ACCOUNT_TRADE_TYPE_DEPOSIT));
    }

    /**
     * 查看消费记录
     *
     * @param detailPage
     * @param userId
     * @return
     */
    @Override
    public IPage<UserAccountDetail> findUserConsumePage(Page<UserAccountDetail> detailPage, Long userId) {
        return userAccountDetailMapper.selectPage(detailPage, new LambdaQueryWrapper<UserAccountDetail>().eq(UserAccountDetail::getUserId, userId).eq(UserAccountDetail::getTradeType, SystemConstant.ACCOUNT_TRADE_TYPE_MINUS));
    }

}
